﻿var map = Default.map;
var medals_data = [];
var region_cptrs = [];
var prev_regions = [];
var cMapping = {}; // Mapping from competitor code to medal data. 
var oMapping = {}; // Mapping from competitor code to map overalays.
var default_sortby = "gold";
var num_top = 5;
var region_sortby = default_sortby;
var current_selected_country = null;

var $ = Go.$;
var moveListener;

String.prototype.strip = function(){
  return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
function domSetStyle(obj, styles){
  for(var s in styles) if(styles.hasOwnProperty(s)){
    obj.style[s] = styles[s];
  }
}

function MedalTab(isActive){
  if(isActive) this.active();
}
window.MedalTab = MedalTab;
MedalTab.prototype = new GoTab(Default.key.medal, {level:1}, false);

MedalTab.prototype.loadStaticData = function(){
    var url = "http://www.gmodules.com/ig/images/olympics/medals.js";
    Go.loadData(url, GEvent.callback(this, this.loadStaticDataCallback));
}

MedalTab.prototype.loadStaticDataCallback = function(data){
  if(data)  {
    try{
        eval('medals_data ='+ data);
    }
    catch(e){
        return;
    }
  } else return;//alert("Data server not responding (medals_data not loading)");
  if(medals_data && medals_data["MedalCounts"])
    medals_data = medals_data["MedalCounts"];
  var res = [];
  if(medals_data.length){
    for(var i = 0; i < medals_data.length; i++){
      medal = medals_data[i] || {};
      if(medal.ioc){
         medal["gold"] = medal["gold"] || 0;
         medal["silver"] = medal["silver"] || 0;
         medal["bronze"] =medal["bronze"] || 0;
         res.push(medal);
      }
    }
    if(res.length == 0){
      return;
    }
  }
  else{
      medals_data = [];
      return;
  }
  
  medals_data = res;
  genCptrsMapping();
  refreshMedalTable("global_pane", default_sortby);
  refreshMedalTable("complete_list", default_sortby, medals_data.length);
  updateViewPort(map.getBounds());
}

MedalTab.prototype.loadDataCallback = function(data){
  if(data)  {
    try{
        eval('medals_data ='+ data);
    }
    catch(e){
        this.loadStaticData()
        return;
    }
  }
  else{ 
    this.loadStaticData();
    return;//alert("Data server not responding (medals_data not loading)");
  }
  if(medals_data && medals_data["MedalCounts"])
    medals_data = medals_data["MedalCounts"];
  var res = [];
  if(medals_data.length){
    for(var i = 0; i < medals_data.length; i++){
      medal = medals_data[i] || {};
      if(medal.ioc){
         medal["gold"] = medal["gold"] || 0;
         medal["silver"] = medal["silver"] || 0;
         medal["bronze"] =medal["bronze"] || 0;
         res.push(medal);
      }
    }
    if(res.length == 0){
      return;
    }
  }
  else{
      medals_data = [];
      return;
  }
  
  medals_data = res;
  genCptrsMapping();
  refreshMedalTable("global_pane", default_sortby);
  refreshMedalTable("complete_list", default_sortby, medals_data.length);
  updateViewPort(map.getBounds());
}

MedalTab.prototype.load = function(){
  for(var ioc in coords_data){ 
    coords_data[ioc].anchor = new GLatLng(coords_data[ioc].lat, coords_data[ioc].lng);
  }
  try{
    if (Default.isDebug){
      Go.loadData(Default.baseUrl + 'data/medals.json', GEvent.callback(this, this.loadDataCallback));
    }
    else{
      var url = "http://sports.scores.gadget.googlepages.com/medals.js"; 
      //var url = Default.dataUrl + 'type=medal';
      //var url = "http://www.google.cn/ig/images/olympics/medals.js";
      Go.loadData(url, GEvent.callback(this, this.loadDataCallback));
    }
  }catch(err){alert(err);}
  moveListener = GEvent.addListener(map, "moveend", function() {
    updateViewPort(map.getBounds());
  });
  GEvent.addDomListener(document.body, 'click', function(){searchCountries('');});
  GEvent.addDomListener($('country_input'), 'keyup', handleKeyEvent);
  GEvent.addDomListener($("country_search"), "click", function(){
    handleKeyReturn($('searchresult'));
  });

  $('searchresult').highlight = -1; //
}
MedalTab.prototype.reload = function(){
  updateViewPort(map.getBounds());
  moveListener = GEvent.addListener(map, "moveend", function() {
    updateViewPort(map.getBounds());
  });
}
MedalTab.prototype.clear = function(){
  GEvent.removeListener(moveListener);
  if(prev_regions){
    for(var i = 0; i < prev_regions.length; i++){
      coords_data[prev_regions[i]].overlay.show(false);
    }
    prev_regions = Array();
  }
}

function GraphOverlay(center, title, ioc, values){
    this.center = center;
    this.title = title;
    this.ioc = ioc;
    this.values = values;

    GraphOverlay.MEDAL_OVERLAYS_MAP = {};
	
    for(var i=0; i<GraphOverlay.MEDAL_OVERLAYS.length; i++){
        GraphOverlay.MEDAL_OVERLAYS_MAP[GraphOverlay.MEDAL_OVERLAYS[i]] = i;
    }
}
GraphOverlay.MEDAL_OVERLAYS = ['gold', 'silver', 'bronze', 'total','gold_h', 'silver_h', 'bronze_h', 'total_h'];

GraphOverlay.prototype = new GOverlay();
GraphOverlay.prototype.initialize = function(map){
    var div = document.createElement("div");
    div.style.position = 'absolute';
    div.innerHTML = '<span class="graph_overlay" style="background-position:'
      + FindIconPosition() + '"><span class="overlay_text">'
      + (this.values[region_sortby]) + '</span></span>';

    //div.innerHTML = '<span class="graph_overlay"><span class="overlay_text">'
    //              + (this.values.total) + '</span></span>';
    map.getPane(G_MAP_MAP_PANE).appendChild(div);
    this.map_ = map;
    this.div_ = div;
    div.overlay = this;
    GEvent.addDomListener(this.div_, 'mouseover', function(event){
        showInfo(this.overlay.ioc, true);      
        var pane_id = "region_li_" + this.overlay.ioc;
        if ($(pane_id)){
            $(pane_id).style.background = '#d5ddf3';
        }
        pane_id = "search_" + this.overlay.ioc;
        if ($(pane_id)){
            $(pane_id).style.background = '#d5ddf3';
        }
    });
    GEvent.addDomListener(this.div_, 'mouseout', function(event){
        showInfo(this.overlay.ioc, false);
        var pane_id = "region_li_" + this.overlay.ioc; 
        if ($(pane_id)){
            $(pane_id).style.background = '';
        }
    });
    GEvent.addDomListener(this.div_, 'click', function(event){
        refreshSearchPane(this.overlay.ioc);
        showCountry(this.overlay.ioc);
    });
}
GraphOverlay.prototype.update = function(){
  this.div_.firstChild.style.backgroundPosition = FindIconPosition();
  this.div_.firstChild.firstChild.innerHTML = this.values[region_sortby];
}
GraphOverlay.prototype.remove = function(){
    map.getPane(G_MAP_MAP_PANE).removeChild(this.div_);
}
GraphOverlay.prototype.copy = function(){
    return new GraphOverlay(this.center, this.width, this.height,this.title, this.values);
}
GraphOverlay.prototype.redraw = function(force){
    center = this.map_.fromLatLngToDivPixel(this.center);
    this.div_.style.top = (center.y - 10) + 'px';
    this.div_.style.left = (center.x - 18) + 'px';
}
GraphOverlay.prototype.show = function(visible){
  this.div_.style.display = visible ? "" : "none";
}

function genInfoWindowTableColumn(width, name, bold){
    return '<span style="display:block;width:'+ width 
          + ';float:left;text-align:right;">'+ (bold == 'b'? '<b>':'') 
          + name + (bold == 'b'? '</b>': '') + '</span>';
}
function showInfo(ioc, show){
    overlay = coords_data[ioc].overlay;
    if (!overlay) return;
    var span = overlay.div_.firstChild;
    if(show){
        span.className += ' graph_overlay_h';
        span.style.backgroundPosition = FindIconPosition('_h');
        overlay.div_.style.top = overlay.div_.offsetTop - 2 + "px";
        overlay.div_.style.left = overlay.div_.offsetLeft - 2 + "px";
    }else{
        span.className = span.className.replace(' graph_overlay_h', '');
        span.style.backgroundPosition = FindIconPosition();
        overlay.div_.style.top = overlay.div_.offsetTop + 2 + "px";
        overlay.div_.style.left = overlay.div_.offsetLeft + 2 + "px";
    }
}
function genMedalImgStr(name){
   var img_src = getImgUrl(name.toLowerCase() + "-unselected.png");
   return '<img border=0 src="' + img_src + '" />';
}
function genInfoWindowDetailTable(events){
    var str = '<tr valign="top">' 
        + genMedalTableContent('70', '&nbsp;', 'left', 'b')
        + genMedalTableContent('130', '&nbsp;', 'left', 'b')
        + genMedalTableContent('36', '&nbsp;', 'left', 'b')
        + '</tr>';
    for (var i = 0; i < events.length; i ++){
        str += '<tr valign="top">'
            + genMedalTableContent('70', events[i].sport)
            + genMedalTableContent('130',events[i].event)
            + genMedalTableContent('36', genMedalImgStr(events[i].medal), 'center')
            + '</tr>';
    }
    var html = '<div id="info_detail" style="height:190px; overflow:auto;">'
             + '<table id="info_more" class="sample">' + str +'</table></div>';
    return html;
}
function genInfoWindowSummaryTable(events){
    var str = '<tr valign="top">' 
        + genMedalTableContent('70', 'Sport', 'left', 'b')
        + genMedalTableContent('130', 'Event', 'left', 'b')
        + genMedalTableContent('36', 'Medal', 'left', 'b')
        + '</tr>';
    for (var i = 0; i < events.length; i ++){
        str += '<tr valign="top">'
            + genMedalTableContent('70', events[i].sport)
            + genMedalTableContent('130',events[i].event)
            + genMedalTableContent('36', genMedalImgStr(events[i].medal), 'center')
            + '</tr>';
    }
    var html = '<div id="info_summary" style="height:190px; overflow:auto;">'
             + '<table id="info_more" class="sample">' + str +'</table></div>'
    return html;
}
function showInfoDetail_wait(ioc){
  var overlay = coords_data[ioc].overlay; 
  var detail_data = {};
  var url = "http://www.google.cn/ig/olympics?type=cm&oe=utf8&hl=" + Default.lang + "&country=" + ioc;
  ////<<<<<<<<< switch when static files are live
  //var url = "http://www.gmodules.com/ig/images/olympics/cm-" + ioc.toLowerCase() + ".js";
   try{Go.loadData(url, function(transport){
   	    var html = "";
   	    var img = IconFactories['flag'].getIcon(ioc, true, "display:-moz-inline-box;float:left;") 
                + '<span style="padding-left:4px;"><b>' + Go.getLocalLabel(ioc) + '</b></span>';
        if(transport){  // else return;//alert("Data server not responding, please try again.");
          eval('var detail_data='+ transport);
          if(detail_data.Event && detail_data.Event.length != 0){
             html = img + '<br/>' + genInfoWindowDetailTable(detail_data.Event);
             //html = img + '<br/>' + genInfoWindowSummaryTable(detail_data.Event)
             //      + genInfoWindowDetailTable(detail_data.Event)
             //      + '<div id="info_control" onclick="showDetail();"><font color="blue">' + Go.getLocalLabel("detail") + '</font></div>';
          }
        }
        if(html == ""){
           html = img + '<br/><div style="margin-top:10px">' + Go.getLocalLabel("noresult") + '</div>' 
        }
        var content = Go.$n("div", null, "", html);
        content.style.width = "245px";
        map.openInfoWindow(overlay.center, content);
    });}catch(err){alert(err);}
}

function showInfoDetail(ioc){
  var overlay = coords_data[ioc].overlay;
  var cptr = cMapping[ioc];
  var html = '<div>'
      + IconFactories['flag'].getIcon(ioc, true, "display:-moz-inline-box;float:left;") 
      + '<span style="padding-left:4px;"><b>' + Go.getLocalLabel(ioc) + '</b></span><br>'
      + '</div>'
      + '<div align="center" style="margin-top:20px"><table width="120">'
      + '<tr>'
      + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("gold-unselected.gif") + '"/>', 'right')
      + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("silver-unselected.gif") + '"/>', 'right')
      + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("bronze-unselected.gif") + '"/>', 'right')
      + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("total-unselected.gif") + '"/>', 'right')
      + '</tr><tr>'
      + genMedalTableContent('30', cptr.gold, 'right')
      + genMedalTableContent('30', cptr.silver, 'right') 
      + genMedalTableContent('30', cptr.bronze, 'right')
      + genMedalTableContent('30', cptr.total, 'right')
      + '</tr></table></div>';
  var content = Go.$n("div", null, "", html);
  content.style.width = "180px";
  map.openInfoWindow(overlay.center, content);
}

function showDetail(){
    document.getElementById("info_summary").style.display = "none";
    document.getElementById("info_detail").style.display = "";
    document.getElementById("info_control").innerHTML = '<font color="blue">'+Go.getLocalLabel("summary")+'</font>';
    document.getElementById("info_control").onclick=showSummary;
}
function showSummary(){
    document.getElementById("info_summary").style.display = "";
    document.getElementById("info_detail").style.display = "none";
    document.getElementById("info_control").innerHTML = '<font color="blue">'+Go.getLocalLabel("detail")+'</font>';
    document.getElementById("info_control").onclick=showDetail;
}
function isContained(region_cptrs, ioc){
    for (var i=0; i<region_cptrs.length; i++){
        if(region_cptrs[i].ioc == ioc){
            return true;
        }
    }
    return false;
}
function updateViewPort(bounds, sortby){
    sortby = sortby || region_sortby;
    region_sortby = sortby;
    var cptrs = [];
    for(var ioc in coords_data){
        if (bounds.containsLatLng(coords_data[ioc].anchor)){
            cptrs.push(ioc);
        }
    }
    region_cptrs = getTopCptrs(cptrs, sortby, num_top);
    if(current_selected_country && !isContained(region_cptrs, current_selected_country) 
      && ArrIndex(cptrs, current_selected_country) >= 0){
        region_cptrs.push(cMapping[current_selected_country]);
    }
    if (region_cptrs.length == 0){
        $('region_div').style.display = "none";
    }
    else{
        $('region_div').style.display = "";
    }
    refreshMedalTable("region_pane",sortby, num_top);
    refreshRegionMap();
}
function domImmediateDescendants(element){
    var e = element.firstChild;
    if(!e) return [];
    var result = [];
    while(e){
        if(e.nodeType == 1){
            result.push(e);
        }
        e = e.nextSibling;
    }
    return result;
}
function handleKeyReturn(element) {
   if (element.style.display =="none" || domImmediateDescendants(element).length == 0){
        var part = $('country_input').value;
        if (part =='') { current_selected_country = null; return;}
        for(var i=0; i<medals_data.length; ++i){
            name = Go.getLocalLabel(medals_data[i].ioc);//cptr.ioc.toUpperCase() //medals_data[i].country;
            index = name.toLowerCase().indexOf(part.toLowerCase());
            if(index >= 0){
                showCountry(medals_data[i].ioc);
                //bug:1320733
                $('country_input').value = Go.getLocalLabel(medals_data[i].ioc);
                break;
            }
        }
        return;
    }
    var items = domImmediateDescendants(element);
    var index = (element.highlight<0)?0:element.highlight;
    for(var i=0; i<items.length; ++i){
        if(i==index){
            var ioc = items[index].id.substr(2);
            showCountry(ioc);
            $('country_input').value = Go.getLocalLabel(ioc);
            searchCountries('');
            break;
        }
    }
}
function handleKeyEvent(event){
    if(!event) event = window.event;
    var element = $('searchresult');
    switch(event.keyCode)
    {
    case 38:
        -- element.highlight;
        $('country_input').value = highlightSearchResult(element);
        break;
    case 40:
        ++ element.highlight;
        $('country_input').value = highlightSearchResult(element);
        break;
    case 13:
        handleKeyReturn(element);
        break;
    default:
        element.highlight = -1;
        searchCountries($('country_input').value);
    }
}
function highlightSearchResult(pane){
    var items = domImmediateDescendants(pane);
    for(var i = 0; i < items.length; ++ i){
        if(i == pane.highlight){
            domAddClassName(items[i], 'highlight');
            if(i>5){
                var odis = items[i].style.display;
                items[i].style.display = "inline-block";
                pane.scrollTop = items[i].clientHeight * (i-5);
                items[i].style.display = odis;
            }
	         else{
                pane.scrollTop = 0;
            }
        }
	      else{
            domRemoveClassName(items[i], 'highlight');
        }
    }
    if(pane.highlight < 0 || pane.highlight > items.length - 1){
        pane.highlight = -1;
        return pane.search_word;
    }
    else{
        return Go.getLocalLabel(items[pane.highlight].id.substr(2));
    }
}
function searchCountries(word){
    var part = word.strip();
    var element = $('searchresult');
    element.search_word = word;
    if(part.length == 0){
        element.style.display = "none";
        element.innerHMTL = "";
        return;
    }
    var html = "";
    var name = "";
    var index = -1;
    var total = 0;
    var added = [];
    var i = 0;
    for(i = 0; i < medals_data.length; ++i){
        name = Go.getLocalLabel(medals_data[i].ioc.toUpperCase());
        index = name.toLowerCase().indexOf(part.toLowerCase());
        if(index >= 0){
            ++ total;
            added.push(medals_data[i].ioc);
            html += '<div id="__' + medals_data[i].ioc + '" class="country_title'
                 + ((i==element.highlight)?' highlight':'') + '" onmouseover="domAddClassName(this, \'highlight\');"'
                 + ' onmouseout="domRemoveClassName(this, \'highlight\');"'
                 + ' onclick="$(\'country_input\').value = Go.getLocalLabel(\'' + medals_data[i].ioc + '\');showCountry(\'' 
                 + medals_data[i].ioc + '\'); searchCountries(\'\');">'
                 + name.substring(0, index) + '<b>'
                 + name.substring(index, index+part.length) + '</b>'
                 + name.substring(index+part.length, name.length) + '</div>';
        }
    }
    if(ArrIndex(added, part.toUpperCase()) < 0 && part.toUpperCase() in coords_data){
          ++ total;
            html += '<div id="__' + part.toUpperCase() + '" class="country_title'
                 + ((i==element.highlight)?' highlight':'') + '" onmouseover="domAddClassName(this, \'highlight\');"'
                 + ' onmouseout="domRemoveClassName(this, \'highlight\');"'
                 + ' onclick="$(\'country_input\').value = Go.getLocalLabel(\'' + medals_data[i].ioc + '\');showCountry(\'' 
                 + part.toUpperCase() + '\'); searchCountries(\'\');">' + Go.getLocalLabel(part.toUpperCase()) +  '</div>';          
    }
    if(total == 0){
        element.innerHTML = html;
        element.style.display = "none";
        return;
    }
    domSetStyle(element, {height: "auto", width: "200px"});
    if(total > 10){
        domSetStyle(element, {height:"120px", overflow:"auto"});
    }
    element.style.display = "";
    element.innerHTML = html;
}

function domHasClassName(element, className){
    var elementClassName = element.className;
    return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
}

function domAddClassName(element, className) {
    if (!domHasClassName(element, className))
      element.className += (element.className ? ' ' : '') + className;
    return element;
}

function domRemoveClassName(element, className) {
    element.className = element.className.replace(
      new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ');
    return element;
}


function getImgUrl(imageName) {
  return Default.imageUrl + "icons/" + imageName;
}

function refreshSearchPane(ioc){
    var cptr = cMapping[ioc];
    var fav_cptrs = Go.getFavo(Default.key.medal);
    if (ArrIndex(fav_cptrs, cptr.ioc) >= 0){
        star_img_src = getImgUrl("starred.gif");
    }
    else{
        star_img_src = getImgUrl("star.gif");
    }
    var star_str = '<img class="star" id="_star'+ cptr.ioc + '" src="' 
                 + star_img_src + '" onclick="handleStar(event);"/>';
    star_str = '&nbsp;'; // To be deleted on launch!
    var row = '<tr>' 
            + genMedalTableContent('23', '&nbsp;')
            + genMedalTableContent('25', '&nbsp;')
            + genMedalTableContent('68', '&nbsp;')
            + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("gold-unselected.gif") + '"/>', 'right')
            + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("silver-unselected.gif") + '"/>', 'right')
            + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("bronze-unselected.gif") + '"/>', 'right')
            + genMedalTableContent('30', '<img border=0 src="' + getImgUrl("total-unselected.gif") + '"/>', 'right')
            + '</tr>'
            + '<tr id="search_'+cptr.ioc+'" valign="top" style="cursor:pointer;background: #d5ddf3;"'
            + ' onmouseover="showInfo(\'' + cptr.ioc +'\', true);"'
            + ' onmouseout="showInfo(\'' + cptr.ioc +'\', false);"'
            + ' onclick="showCountry(\'' + cptr.ioc + '\');">'
            + genMedalTableContent('23', star_str) 
            + genMedalTableContent('25', IconFactories['flag'].getIcon(cptr.ioc, true, 'margin-right:12px'))
            + genMedalTableContent('68', '<a href="" onclick="return false;">' + Go.getLocalLabel(cptr.ioc.toUpperCase())/*cptr.country*/ + '</a>')
            + genMedalTableContent('30', cptr.gold, 'right')
            + genMedalTableContent('30', cptr.silver, 'right') 
            + genMedalTableContent('30', cptr.bronze, 'right')
            + genMedalTableContent('30', cptr.total, 'right')
            + '</tr>';
	    $('search_pane').innerHTML = '<table class="medaltable">' + row + '</table>';
    $('search_div').style.display = '';
}
function showCountry(ioc){
    current_selected_country = ioc;
    //map.panTo(new GLatLng(coords_data[ioc].lat, coords_data[ioc].lng));
    map.setCenter(new GLatLng(coords_data[ioc].lat, coords_data[ioc].lng));
    if (! coords_data[ioc].overlay){
        var medals = cMapping[ioc];
        coords_data[ioc].overlay = new GraphOverlay(coords_data[ioc].anchor, coords_data[ioc].name, ioc,
        medals);
    }
    refreshSearchPane(ioc);
    showInfoDetail(ioc);
    $('searchresult').innerHTML = '';
}
function refreshRegionMap(){
    var exist_set = [];
    var add_set = [];
    var regions = region_cptrs;
    for (var i = 0; i < regions.length; i ++){
        if(ArrIndex(prev_regions, regions[i].ioc) >= 0){
            exist_set.push(regions[i].ioc);
        }
        else{
            add_set.push(regions[i].ioc);
        }
    }
    for (var i= 0; i < add_set.length; i ++){
        var ioc = add_set[i];
        if (!coords_data[ioc].overlay){
            var medals = cMapping[ioc];
            coords_data[ioc].overlay = new GraphOverlay(coords_data[ioc].anchor, coords_data[ioc].name, ioc,
             medals);
        }
        map.addOverlay(coords_data[ioc].overlay);
    } 
    for (var i = 0; i < prev_regions.length; i ++){
        if (ArrIndex(exist_set, prev_regions[i]) == -1){
            map.removeOverlay(coords_data[prev_regions[i]].overlay);
        }
    }
    for (var i= 0; i < exist_set.length; i ++){
        coords_data[exist_set[i]].overlay.update();
    } 
    prev_regions = [];
    for (var i = 0; i < regions.length; i ++){
        prev_regions[i] = regions[i].ioc;
    }
}
function genRegionMedalTableColumn(sortby){
    sortby = sortby.toLowerCase();
    var str = '<a href="" class="nondeco" onclick="updateViewPort(map.getBounds(), \'' 
            + sortby +'\'); return false;"><img border=0 src="' + getImgUrl(sortby +"-unselected.gif") + '"/></a>';
    return str;
}
function genGlobalMedalTableColumn(pane_name, sortby, max_num){
    sortby = sortby.toLowerCase();
    var str = '<a href="" class="nondeco" onclick="refreshMedalTable(\'global_pane\', \'' + sortby 
            + '\', \'5\'); refreshMedalTable(\'complete_list\',\''+ sortby 
            + '\', medals_data.length);return false;"><img border=0 src="' + getImgUrl(sortby +"-unselected.gif") + '"/></a>';
    return str;
}
function genMedalTableColumn(sortby, pane){
    if(pane){
        return '<a href="" class="nondeco" onclick="updateViewPort(map.getBounds(), \'' 
            + sortby +'\'); return false;"><img border=0 src="' + getImgUrl(sortby + "-unselected.gif") + '"/></a>';
    }
    else{
        return '<a href="" class="nondeco" onclick="refreshMedalTable(\'global_pane\', \'' + sortby 
            + '\', \'5\'); refreshMedalTable(\'complete_list\',\''+ sortby 
            + '\', medals_data.length);return false;"><img border=0 src="' + getImgUrl(sortby + "-unselected.gif") + '"/></a>';
    }
}
function genMedalTableContent(width, name, align, bold){
    align = align || 'left';
    var str = '<td width="'+ width +'px" align="'+ align +'">' + (bold == 'b' ? '<b>' : '') 
            + name + (bold == 'b' ? '</b>' : '') + '</td>';
    return str;
}
function genMedalTableFirstRow(str_array){
    return ('<tr>' 
           + genMedalTableContent('23', '&nbsp;')
           + genMedalTableContent('25', '&nbsp;')
           + genMedalTableContent('68', '&nbsp;')
           + genMedalTableContent('30', str_array['gold'], 'right')
           + genMedalTableContent('30', str_array['silver'], 'right')
           + genMedalTableContent('30', str_array['bronze'], 'right')
           + genMedalTableContent('30', str_array['total'], 'right')
           + '</tr>');
}
function genMedalTableRow(s1, s2, s3, cptr, bold){
    return ( genMedalTableContent('23', s1) 
           + genMedalTableContent('25', s2)
           + genMedalTableContent('68', s3)
           + genMedalTableContent('30', cptr.gold, 'right', bold['gold'])
           + genMedalTableContent('30', cptr.silver, 'right', bold['silver']) 
           + genMedalTableContent('30', cptr.bronze, 'right', bold['bronze']) 
           + genMedalTableContent('30', cptr.total, 'right', bold['total']));
}
function genMedalTableEventAction(ioc, pane){
    var id_str = pane?'region_li':'global_li';
    var s1 = '<tr class="region_li" id="'+ id_str + ioc + '" valign="top"';
    var s2 = ' onmouseover="' + (pane?'showInfo(\'' + ioc +'\', true);':'') + 'this.style.background=\'#d5ddf3\';"';
    var s3 = ' onmouseout="' + (pane?'showInfo(\'' + ioc +'\', false);':'') + 'this.style.background=\'\';"';
    var s4 = ' onclick="refreshSearchPane(\'' + ioc + '\');showCountry(\'' + ioc + '\');">';
    return s1 + s2 + s3 + s4;
}
function refreshMedalTable(pane_name, psortby, num){
    var max_num = ((typeof(num) == "undefined")||(num == null)) ? 5 : num;
    var sortby = psortby.toLowerCase();
    var str = {};
    var sortby_keys = ['gold', 'silver', 'bronze', 'total'];
    if (pane_name == "global_pane" || pane_name == "complete_list"){
        for (var i = 0; i < sortby_keys.length; i ++)
            str[sortby_keys[i]] = genGlobalMedalTableColumn(pane_name,sortby_keys[i], max_num);
    }
    if (pane_name == "region_pane"){
        for (var i = 0; i < sortby_keys.length; i ++)
            str[sortby_keys[i]] = genRegionMedalTableColumn(sortby_keys[i]);
    }
    var bold = {'gold':'', 'silver':'', 'bronze':'', 'total':''};
    str[sortby] = '<img border=0 src="' + getImgUrl(sortby + "-selected.gif") + '"/>'; 
    bold[sortby] = 'b';

    var data = [];
    var pane_li = null; 
    if (pane_name == "region_pane"){
        data = region_cptrs;
        pane_li = "region_li_";
    } 
    if (pane_name == "global_pane" || pane_name == "complete_list"){
        data = medals_data;
        if(pane_name == "global_pane"){
            data.sort(compare(sortby));
        }
        if (pane_name == "global_pane") {
            pane_li = "global_li_";
        }
        else{
            pane_li = "complete_li_";
        }
    }
    var pane = $(pane_name);

    var row1 = '<tr>' 
             + genMedalTableContent('23', '&nbsp;')
             + genMedalTableContent('25', '&nbsp;')
             + genMedalTableContent('68', '&nbsp;')
             + genMedalTableContent('30', str['gold'], 'right')
             + genMedalTableContent('30', str['silver'], 'right')
             + genMedalTableContent('30', str['bronze'], 'right')
             + genMedalTableContent('30', str['total'], 'right')
             + '</tr>';

    var fav_cptrs = Go.getFavo(Default.key.medal);
    for(var i = 0; i < data.length && i < max_num; i ++){
        var cptr = data[i];
        var row = '<tr class="region_li" id="' + pane_li + cptr.ioc + '" valign="top"';
        if (pane_li == "region_li_"){
            row += ' onmouseover="this.style.background=\'#d5ddf3\';showInfo(\'' + cptr.ioc +'\', true);"'
                + ' onmouseout="this.style.background=\'white\';showInfo(\'' + cptr.ioc +'\', false);"'                                        
                + ' onclick="showCountry(\'' + cptr.ioc + '\');">';
        }
        else{
            row += ' onmouseover="this.style.background=\'#eae8e8\';" onmouseout="this.style.background=\'\';"'
                +  ' onclick="showCountry(\'' + cptr.ioc + '\');">';
        }
        if (ArrIndex(fav_cptrs, cptr.ioc) >= 0){
            star_img_src =  getImgUrl("starred.gif");
        }
        else{
            star_img_src = getImgUrl("star.gif");
        }
        var star_str = '<img class="star" id="star_'+ cptr.ioc + '" src="' + star_img_src + '" onclick="handleStar(event);"/>';
        if (pane_name == "global_pane" || pane_name == "complete_list"){
            star_str = (i + 1) + '.';
        }
        star_str = '&nbsp;'; // To be deleted on launch!
        row += genMedalTableContent('23', star_str)
            + genMedalTableContent('25', IconFactories['flag'].getIcon(cptr.ioc, true, 'margin-right:12px')) 
            + genMedalTableContent('68', '<a href="" onclick="return false;">' + Go.getLocalLabel(cptr.ioc.toUpperCase()) + '</a>')
            + genMedalTableContent('30', cptr.gold, 'right', bold['gold'])
            + genMedalTableContent('30', cptr.silver, 'right', bold['silver']) 
            + genMedalTableContent('30', cptr.bronze, 'right', bold['bronze']) 
            + genMedalTableContent('30', cptr.total, 'right', bold['total']);
        row += '</tr>';
        row1 += row;
    }
    pane.innerHTML = '<table class="medaltable">' + row1 + '</table>';
}
function showCompleteList()
{
    $('global_div').style.display = 'none';
    $('complete_div').style.display = '';
    $('list_trigger_more').style.display = "none";
    $('list_trigger_less').style.display = "";
}
function showShortList(){
    $('global_div').style.display = '';
    $('complete_div').style.display = 'none';
     $('list_trigger_more').style.display = "";
    $('list_trigger_less').style.display = "none";
}
function handleStar(e){
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    var elem;
    if (e.target){ 
        elem = e.target; 
    }
    else{
        elem = e.srcElement; 
    }
    var ioc = elem.id.substr(5);
    var fav_cptrs = Go.getFavo(Default.key.medal);
    var id1 = '_star' + ioc;
    var id2 = 'star_' + ioc;
    if (ArrIndex(fav_cptrs, ioc) < 0){    
        Go.addFavo(ioc, Default.key.medal);
        //elem.src = getImgUrl("starred.gif");
        if (typeof($(id1)) != "undefined" && $(id1) != null) $(id1).src = getImgUrl("starred.gif");
        if (typeof($(id2)) != "undefined" && $(id2) != null) $(id2).src = getImgUrl("starred.gif");
    }
    else{
        Go.removeFavo(ioc, Default.key.medal);
        if (typeof($(id1)) != "undefined" && $(id1) != null) $(id1).src = getImgUrl("star.gif");
        if (typeof($(id2)) != "undefined" && $(id2) != null) $(id2).src = getImgUrl("star.gif");
    }
}
function compare(sortby, c1, c2){
    return function(c1, c2){
      if (c1 && c2 &&
	      c1.ioc && coords_data[c1.ioc] && coords_data[c1.ioc].name &&
		  c2.ioc && coords_data[c2.ioc] && coords_data[c2.ioc].name) {
        c1.gold = c1.gold || 0;
		c2.gold = c2.gold || 0;
		c1.silver = c1.silver || 0;
		c2.silver = c2.silver || 0;
		c1.bronze = c1.bronze || 0;
		c2.bronze = c2.bronze || 0;
        var g = c1.gold   == c2.gold ? 0 : (c1.gold < c2.gold ? 1 : -1);
        var s = c1.silver == c2.silver ? 0 : (c1.silver < c2.silver ? 1 : -1);
        var b = c1.bronze == c2.bronze ? 0 : (c1.bronze < c2.bronze ? 1 : -1);
        var n = (coords_data[c1.ioc].name < coords_data[c2.ioc].name)? -1 : 1;
        switch (sortby.toLowerCase())
        {
        case "gold":
          return g*8 + s*4 + b*2 + n;
        case "silver":
          return s*8 + g*4 + b*2 + n;
        case "bronze":
          return b*8 + g*4 + s*2 + n;
        case "total":
          t = (c1.gold + c1.silver + c1.bronze) - (c2.gold + c2.silver + c2.bronze);
          t = t == 0 ? 0 : ( t < 0 ? 1 : -1);
          return t*16 + g*8 + s*4 + b*2 + n;
        default:
          t = (c1.gold + c1.silver + c1.bronze) - (c2.gold + c2.silver + c2.bronze);
          t = t == 0 ? 0 : ( t < 0 ? 1 : -1);
          return t*16 + g*8 + s*4 + b*2 + n;
        }
      }
      return 0;
    }
}

function getTopCptrs(ioc_codes, sortby, num){
    var cptrs_data = [];
    for (var i = 0; i < ioc_codes.length; i ++){
        if (cMapping[ioc_codes[i]]){
            cptrs_data.push(cMapping[ioc_codes[i]]);
        }
    }
    if (cptrs_data.length < 1) 
        return [];
    cptrs_data.sort(compare(sortby));
    num = cptrs_data.length >= num ? num : cptrs_data.length;
    return cptrs_data.slice(0, num);
}
function genCptrsMapping(){
    for (var i = 0; i < medals_data.length; i ++){
        cMapping[medals_data[i].ioc] = medals_data[i];
    }
    for (var ioc in coords_data){
      if(typeof(cMapping[ioc]) == "undefined" || cMapping[ioc] == null){
        var tmp = {"ioc":ioc,"gold":0,"silver":0,"bronze":0,"total":0};
        medals_data.push(tmp);
        cMapping[ioc] = tmp;
      }
    }
}
function FindIconPosition(hi){
  hi = hi || "";
  var index = GraphOverlay.MEDAL_OVERLAYS_MAP[region_sortby + hi];
  var x = -45 * Math.floor(index % 4);
  var y = -32 * Math.floor(index / 4); 
  return (x + 'px ' + y + 'px');
}




//added by Chenfei, and be used by star.js, hope can integrate with other functions in medal.js
function refreshStarredMedalTable(pane,countries){
  if(typeof(medals_data) == "undefined" || medals_data == null){
      return;
  }

  var str_g = '<span style="font-weight:bold">Gold</span>';
  var str_s = '<span style="font-weight:bold">Silver</span>';
  var str_b = '<span style="font-weight:bold">Bronze</span>';
  var str_t = '<span style="font-weight:bold">Total</span>';
  
  var data = [];
  var pane_li = null; 
  for(var i = 0; i < countries.length; i++){
      data.push(cMapping[countries[i]]);
  }
  if(data.length == 0) return;
  pane_li = "region_li_";
  
  var row1= '<table class="sample"><thead><tr>' 
          + genMedalTableContent('23', '&nbsp;')
          + genMedalTableContent('25', '&nbsp;')
          + genMedalTableContent('60', '&nbsp;')
          + genMedalTableContent('34', str_g, 'right')
          + genMedalTableContent('34', str_s, 'right')
          + genMedalTableContent('34', str_b, 'right')
          + genMedalTableContent('34', str_t, 'right')
          + '</tr></thead>';
  row1 += '<tbody>';
  for(var i = 0; i < data.length; i ++)
  {
    var cptr = data[i];
    var row = '<tr class="region_li" id="' + pane_li + cptr.ioc + '" valign="top"';
    if (pane_li == "region_li_")
    {
       row += ' onmouseover="showInfo(coords_data[\'' + cptr.ioc +'\'].overlay, true); this.style.background=\'#d5ddf3\';"'
           + ' onmouseout="showInfo(coords_data[\'' + cptr.ioc +'\'].overlay, false);this.style.background=\'\';"'
           + ' onclick="showInfo(coords_data[\'' + cptr.ioc +'\'].overlay, false);showInfoDetail(coords_data[\'' + cptr.ioc + '\'].overlay);"';
    }
    row += ' onmouseover="this.style.background=\'#eae8e8\';" onmouseout="this.style.background=\'\';">';
    var star_str = '<img class="starred" id="star_'+ cptr.ioc + '" style="margin-right:5px" src="img/starred.gif" onclick="handleStar(event);"/>';
    star_str = '&nbsp;'; // To be deleted on launch!
    row += genMedalTableContent('23', star_str) 
        + genMedalTableContent('25', '<img class="pad" src="http://www.google.cn/images/flags/' + cptr.ioc + '.gif"/>')
        + genMedalTableContent('60', '<font color="blue">' + Go.getLocalLabel(cptr.ioc.toUpperCase()) + '</font>')
        + genMedalTableContent('34', cptr.gold, 'right')
        + genMedalTableContent('34', cptr.silver, 'right') 
        + genMedalTableContent('34', cptr.bronze, 'right') 
        + genMedalTableContent('34', cptr.total, 'right');
    row += '</tr>';
    row1 += row;
    var medals = cMapping[cptr.ioc];
    var overlay = new GraphOverlay(coords_data[cptr.ioc].anchor, coords_data[cptr.ioc].name,cptr.ioc,
    {rg:medals.rank, rt:medals.rank, total:medals.gold});
     map.addOverlay(overlay); locas[compitor.ioc] = overlay;
  }
  row1 += '</tbody></table>';
  pane.innerHTML = row1; 
}

function ArrIndex(arr, ele){
    for(var index in arr) if(arr.hasOwnProperty(index)){
        if(arr[index] == ele){
            return index;
        }
    }
    return -1;
}
Default.tabs[Default.key.medal] = new MedalTab(true);
